<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 4/13 0013
 * Time: 14:33
 */

namespace app\api\model;


use think\Model;

class Meituan extends Model
{
    /**
     * 获取签名
     * @param $url
     * @return string
     */
    public function  SignKey($url){
        $signKey="r2wmwbjl2rmjftsh";//TODO SIGNKEY需要更新
        $url = substr($url,strpos($url,"?")+1);
        $urlarr=explode("&", $url);
        foreach ($urlarr as $key => $value) {
            $urlarr[$key] = explode("=", $value);
            if($urlarr[$key][1]==""){
                unset($urlarr[$key]);//删除空参
            }else{
                $urlarr[$key]=implode($urlarr[$key],"");
            }
        }
        sort($urlarr);//重新排序
        $sring=$signKey.implode($urlarr,"");
        return sha1($sring);//获得签名
    }

    /**
     * 获取唯一门店id
     * @return string
     */
    public function ePoiId(){
        $yCode = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
        return $orderSn = $yCode[intval(date('Y')) - 2011] . date('d') . substr(time(), -3) . substr(microtime(), 2, 1) . sprintf('%02d', rand(0, 99));
    }

    /**
     * cURL 连接方法
     * @param $data
     * @param $url
     * @param string $type
     * @return mixed|string
     */
    public function method($data, $url, $type = 'get') {
        $post_data = http_build_query($data);
        if ($type == 'get') {
            $ch = curl_init();
            $url = $url.'?'.$post_data;
            curl_setopt($ch , CURLOPT_URL, $url);
            curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch , CURLOPT_HEADER, 0);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
        } else if ($type == 'post') {
            $ch = curl_init();
            curl_setopt($ch , CURLOPT_URL, $url);
            curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch , CURLOPT_POST, 1);
            curl_setopt($ch , CURLOPT_POSTFIELDS, $post_data);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;

        } else {
            return '请求方式错误';
        }
    }

    /**
     * 发送POST方法
     * @param $url
     * @param $post_data
     * @return mixed
     */
    public function post($url,$post_data){
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $result=json_decode($result,ture);
        $data=$result['data'];
        return $data;
    }

}